/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 05.08.2006
 *
 *************************************************/
package fightplan.business.util;

public class AgeUtil {

	public static final int MIN_AGE = 0;
	public static final int MAX_AGE = 99;
	public static final String ALL_AGE = "Alle";

	public static int parse(String s) throws IllegalArgumentException {
		if (s == null)
			throw new IllegalStateException();
		s = s.trim();
		if (s.length() >= 1 && s.length() <= 2) {
			int age = Integer.parseInt(s);
			return age;
		} else {
			throw new IllegalArgumentException("Altersangaben müssen aus einer gültigen Zahl bestehen. (" + s + ")");
		}
	}

	public static int parseRangeStart(String s) throws IllegalArgumentException {
		if (s == null)
			throw new IllegalStateException(s);
		s = s.trim();
		if (ALL_AGE.equals(s))
			return 0;
		int pos = s.indexOf("-");
		if (pos == 0)
			return MIN_AGE;
		if (pos == -1)
			return parse(s);
		return parse(s.substring(0, pos));
	}

	public static int parseRangeEnd(String s) throws IllegalArgumentException {
		if (s == null)
			throw new IllegalStateException(s);
		s = s.trim();
		if (ALL_AGE.equals(s))
			return MAX_AGE;
		int pos = s.indexOf("-");
		if (pos == s.length() - 1)
			return MAX_AGE;
		if (pos == 0)
			return parse(s.substring(1));
		return parse(s.substring(pos + 1, s.length()));
	}

	public static String format(int age) {
		return "" + age;
	}

	public static String formatRange(int start, int end) {
		if (start <= MIN_AGE) {
			if (end >= MAX_AGE) {
				return "Alle";
			} else {
				return "- " + end;
			}
		} else {
			if (end >= MAX_AGE) {
				return start + " -";
			} else if (start == end) {
				return "" + start;
			} else {
				return start + " - " + end;
			}
		}
	}

	public static String formatRangeForDescription(int start, int end) {
		if (start <= MIN_AGE) {
			if (end >= MAX_AGE) {
				return "Alle";
			} else {
				return "bis " + end + "Jahre";
			}
		} else {
			if (end >= MAX_AGE) {
				return "ab " + start + "Jahre";
			} else if (start == end) {
				return "" + start + "Jahre";
			} else {
				return start + " bis " + end + "Jahre";
			}
		}
	}

}
